#! /usr/bin/env python3

import urlearning.Variable as Variable
from copy import deepcopy

class BayesianNetwork:

    def __init__(self):
        self.name = ""
        self.variables = []
        self.nameToIndex = {}

    def __len__(self):
        return len(self.variables)

    def __getitem__(self, key):
        return self.variables[key]

    def __iter__(self):
        self.cur = 0
        return self

    def __next__(self):
        if self.cur >= len(self):
            raise StopIteration
        r = self[self.cur]
        self.cur += 1
        return r

    def addVariable(self, variableName):
        v = Variable.Variable(self, variableName, len(self.variables))
        self.variables.append(v)
        self.nameToIndex[variableName] = v
        return v
        
    def getVariableCount(self):
        return len(self.variables)
        
    def get(self, variableIndex):
        return self.variables[variableIndex]
        
    def getByName(self, variableName):
        return self.nameToIndex[variableName]
        
    def getVariableIndex(self, variableName):
        return self.getByName(variableName).getIndex()

    def size(self):
        return len(self.variables)

    def getArity(self, index):
        return self.variables[index].getArity()

    def print(self):
        for var in self.variables:
            var.print()

    def toDimacs(self):
        """ This method converts the graph structure of the Bayesian network
            into a Dimacs graph.

            imports:
                urlearning.DimacsGraph
        """
        from urlearning.DimacsGraph import DimacsGraph

        dg = DimacsGraph(len(self), weighted=False, directed=True)
                
        for var in self:
            var_index = var.getIndex()
            
            for par in var.getParents():
                dg.addEdge(par, var_index)

        return dg
